package tcp.test;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

public class SubmitFileTask implements Runnable {
    private Socket socket;
    public SubmitFileTask(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try{
            InputStream is = socket.getInputStream();
            OutputStream os = socket.getOutputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));

            //读取文件名
            String fileName = br.readLine();
            bw.write("名字已读取");
            bw.newLine();
            bw.flush();

            //手动拼接服务端的存储位置,UUID避免文件名重复
            File file = new File("D:\\", UUID.randomUUID().toString() +fileName);
            //读取文件字节
            FileOutputStream fos = new FileOutputStream(file);
            byte[] bys = new byte[1024];
            int len;
            //is是网络流，没有直接关联文件，读取不到文件末尾的-1
            while ((len = is.read(bys)) != -1) {
                fos.write(bys, 0, len);
            }
            fos.close();
            //写反馈消息
            bw.write("上传成功");
            bw.newLine();
            bw.flush();

            socket.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
